package com.goldsign.pay.provider.user.controller;

import com.goldsign.pay.provider.user.to.UserLoginRespDTO;
import com.goldsign.pay.common.log.SysLog;
import com.goldsign.pay.common.to.ServiceResponseDTO;
import com.goldsign.pay.common.util.ApiHelpUtil;
import com.goldsign.pay.common.util.Constant;
import com.goldsign.pay.provider.user.service.UserLoginService;
import com.goldsign.pay.provider.user.to.UserLoginReqDTO;
import com.goldsign.pay.provider.user.util.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by xiaojingjing on 2018/5/17.
 */
@Controller
public class AppLoginController {

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 登录
     * @param userLoginReq
     * @param request
     * @param response
     */
    @RequestMapping("/userLogin")
    public void userLogin(UserLoginReqDTO userLoginReq, HttpServletRequest request, HttpServletResponse response) {
        SysLog.info(request);
        try {
            userLoginReq = userLoginService.initParam(userLoginReq,request);
            SysLog.info("【userLogin】收到的请求参数："+userLoginReq.toString());
            UserLoginRespDTO userLoginRespDTO =  userLoginService.userLogin(userLoginReq);
            User user = userLoginService.handleResult(userLoginRespDTO,userLoginReq);

            ServiceResponseDTO serviceResponse = new ServiceResponseDTO(userLoginRespDTO.getResp_code(),userLoginRespDTO.getResp_msg());
//            serviceResponse.putEntry("user", ObjectUtil.sortMapByKey(ObjectUtil.obj2Map(user)));
            serviceResponse.putEntry("user", user);
            ApiHelpUtil.apiReturn(serviceResponse, response);
        } catch (Exception e) {
            ApiHelpUtil.writeServerError(response, "服务异常");
            e.printStackTrace();
        }
    }

    /**
     * 登出
     * @param tokenId
     * @param request
     * @param response
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/logout")
    public void logout(String tokenId,HttpServletRequest request,HttpServletResponse response) {
        try {
            userLoginService.appLogout(tokenId);
            ServiceResponseDTO serviceResponse = new ServiceResponseDTO(Constant.SUCCESS,"SUCCESS");
            ApiHelpUtil.apiReturn(serviceResponse, response);
        } catch (Exception e) {
            ApiHelpUtil.writeServerError(response, "服务异常");
            e.printStackTrace();
        }
    }
}
